package com.s64.ch06.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.s64.ch06.entity.SysUser;
import com.s64.ch06.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-11-21
 */
@RestController
@RequestMapping("/users")
@CrossOrigin
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;

    @GetMapping
    public Page<SysUser> getAll(SysUser user, int pageNo, int pageSize) {
        /*QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(user.getRealName()), "realName", user.getRealName());
        queryWrapper.eq(user.getRoleId() != null, "roleId", user.getRoleId());*/
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(user.getRealName()), SysUser::getRealName, user.getRealName());
        queryWrapper.eq(user.getRoleId() != null, SysUser::getRoleId, user.getRoleId());
        Page<SysUser> page = sysUserService.page(Page.of(pageNo, pageSize), queryWrapper);
        return page;
    }

    @PostMapping("/add")
    public boolean add(@RequestBody SysUser sysUser) {
        return sysUserService.save(sysUser);
    }

    @DeleteMapping("/del")
    @CacheEvict(cacheNames = "user", key = "'get.' + #id")
    public boolean del(Integer id) {
        return sysUserService.removeById(id);
    }


    @GetMapping("/update/{id}")
    // 用指定的key从缓存中查询数据，如何有就直接返回，否则将方法的返回值缓存
    @Cacheable(cacheNames = "user", key = "'get.' + #id")
    public SysUser get(@PathVariable Integer id) {
        System.out.println("执行get方法：{}" + id);
        return sysUserService.getById(id);
    }

    @PutMapping("/update")
    // 将指定的key方法的返回值放入缓存
    @CachePut(cacheNames = "user", key = "'get.' + #sysUser.id")
    public SysUser update(@RequestBody SysUser sysUser) {
        sysUserService.saveOrUpdate(sysUser);
        return sysUser;
    }
}
